<template>
  <el-dialog :model-value="visible" :before-close="handleClose" :title="title" width="800px">
    <el-form ref="form" :model="newFormData" :rules="rules" label-width="100px">
      <el-form-item label="选项名称" prop="optionName">
        <el-input v-model="newFormData.optionName" class="form-group" placeholder="请输入选项名称" maxlength="50" show-word-limit/>
      </el-form-item>
      <el-form-item label="选项值" prop="optionValue">
        <el-input v-model="newFormData.optionValue" class="form-group" placeholder="请输入选项值" maxlength="50" show-word-limit/>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="newFormData.sort" :min="0" controls-position="right"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm('formData')">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import {optionsEdit} from '@/api/options';

export default {
  name: 'EditOptions',
  props: {
    // route object
    formData: {
      type: Object,
      default: () => {
      }
    },
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      newFormData: {},
      rules: {
        optionName: [
          {required: true, message: '请输入选项名称', trigger: 'blur'}
        ],
        optionValue: [
          {required: true, message: '请输入选项值', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入序号', trigger: 'blur'}
        ]
      }
    };
  },
  mounted() {
    this.newFormData = {...this.formData};
  },
  emits: ['close-callback'],
  methods: {
    handleClose() {
      this.$emit('close-callback');
    },
    submitForm(formName) {
      if (!this.newFormData.optionName || !this.newFormData.optionValue) {
        this.$message({
          type: 'error',
          message: '值不能为空'
        });
        return false;
      }
      this.onSubmit();
    },
    onSubmit() {
      this.loading = true;
      // 编辑
      optionsEdit(this.newFormData
      ).then((res) => {
        this.loading = false;
        this.$message.success(res);
        this.$emit('close-callback', 'success');
      }).catch(() => {
        this.loading = false;
      });
    }
  }
};
</script>
